import React from 'react'
import UnFinishImage from '../../../res/images/web/shared/construction@2x.png'
import './Basketball.css'
import {Tabs} from "antd-mobile";
import {
    getBasketballGameFollowReq,
    getBasketballGameListAllReq,
    getBasketballGameListLiveReq,
    getBasketballGameListReq, getBasketballGameResultReq, getHotReq
} from "../../../apis/goApis";
import BasketballGameCard from "./BasketballGameCard/BasketballGameCard";
import {formatDate, formatDateWithDot, handleDateChange} from "../../../utils/dateService";
import DateTabs from "../../../shared-components/DateTabs/DateTabs";
import {GlobalStore} from "../../../context";
import {connect} from "react-redux";
import LocalStorageService from "../../../utils/LocalStorageService";
import NoDataPage from "../Football/NoDataPage/NoDataPage";
import EmptyStar from "../../../res/images/web/game-room/星形@2x.png";
import moment from "moment";
import HotGameButton from "../Football/HotGameButton/HotGameButton";

class Basketball extends React.Component {
    constructor(props) {
        super(props)
        this.today = formatDate(new Date())
        this.uid = LocalStorageService.get('userid')
        this.state = {
            tabs: [
                {title: '全部',},
                {title: '进行中',},
                {title: '赛程',},
                {title: '赛果',},
                {title: '关注',},
            ],
            tabIndex: 0,
            positions: [0, 0, [0, 3,],],
            list: [
                [],
                [],
                [[], [], [], [],],
                [[], [], [], [],],
                [],
            ],
            fetchStatus: [
                false,
                false,
                [false, false, false, false,],
                [false, false, false, false,],
                false,
            ],
            curList: [],

            // futureDates
            scheduleTabs: [
                {value: this.today, title: '今天', active: true,},
                {value: formatDate(handleDateChange(this.today, 1)), title: formatDateWithDot(handleDateChange(this.today, 1)), active: false,},
                {value: formatDate(handleDateChange(this.today, 2)), title: formatDateWithDot(handleDateChange(this.today, 2)), active: false,},
                {value: formatDate(handleDateChange(this.today, 3)), title: formatDateWithDot(handleDateChange(this.today, 3)), active: false,},
            ],
            scheduleTabsIndex: 0,
            resultTabs: [
                {value: formatDate(handleDateChange(this.today, -3)), title: formatDateWithDot(handleDateChange(this.today, -3)), active: false,},
                {value: formatDate(handleDateChange(this.today, -2)), title: formatDateWithDot(handleDateChange(this.today, -2)), active: false,},
                {value: formatDate(handleDateChange(this.today, -1)), title: formatDateWithDot(handleDateChange(this.today, -1)), active: false,},
                {value: this.today, title: '今天', active: true,},
            ],
            resultTabsIndex: 3,
            markedList: [],
            hot: false,
            hots: [],
        }
        this.timerIdAll = null
        this.timerIdLive = null
    }

    componentDidMount() {
        this.getMarkedList()
        this.all()
        this.initPosition()
        this.fresh()
        this.getHot()
    }

    componentWillUnmount() {
        if (this.timerIdAll) clearInterval(this.timerIdAll)
        if (this.timerIdLive) clearInterval(this.timerIdAll)
    }

    getHot = () => {
        getHotReq()
            .then((res) => {
                const hots = res.data.ok.lq
                this.setState({
                    hots,
                })
            })
    }

    setHot = (value) => {
        this.setState({
            hot: value,
        })
    }

    getMarkedList() {
        if (LocalStorageService.get('isLogin')) {
            getBasketballGameFollowReq({uid: this.uid,})
                .then(resp => {
                    const list = resp.data.ok
                    if (list && list.length > 0) {
                        this.setState({
                            markedList: list,
                        })
                    }

                })
        }
    }

    initPosition() {
        const ps = this.context.gamePagePosition.positions
        this.setState({
            positions: [...ps,],
            scheduleTabsIndex: ps[2][0],
            resultTabsIndex: ps[2][1],
        }, () => {
            const index = ps[1]
            const params = {}
            if (index === 2) {
                params.date = this.state.scheduleTabs[this.state.scheduleTabsIndex].value
            } else if (index === 3) {
                params.date = this.state.resultTabs[this.state.resultTabsIndex].value
            } else if (index === 4) {
                if (LocalStorageService.get('isLogin')) {
                    params.uid = this.uid
                }
            }
            this.getList(ps[1], params)
        })

    }

    getList = (index, params= {}) => {
        const ends = [
            getBasketballGameListAllReq,
            getBasketballGameListLiveReq,
            getBasketballGameListReq,
            getBasketballGameResultReq,
            getBasketballGameFollowReq,
        ]
        // let statusList = this.state.fetchStatus
        // let status = statusList[index]
        const end = ends[index]
        if (end) {
            if (index === 4 && LocalStorageService.get('isLogin') === null) {
                return
            }
            if (index === 0 || index === 1 || index === 4) {
                ends[index] && ends[index](params)
                    .then((resp) => {
                        let list = resp.data.ok
                        let lists = this.state.list
                        lists[index] = list
                        this.setState({
                            list: [
                                ...lists,
                            ],
                            curList: list,
                        }, () => {
                            if (this.state.tabIndex !== index) {
                                this.setState({
                                    tabIndex: index,
                                })
                            }
                            this.props.setCurBasketballList(list,)
                        })
                    })
            } else if (index === 2 || index === 3) {
                const dateTabsActiveIndex = index === 2 ? this.state.scheduleTabsIndex : this.state.resultTabsIndex
                ends[index] && ends[index](params)
                    .then((resp) => {
                        let list = resp.data.ok
                        let lists = this.state.list
                        let dateLists = lists[index]
                        dateLists[dateTabsActiveIndex] = list
                        lists[index] = dateLists
                        this.setState({
                            list: [
                                ...lists,
                            ],
                            curList: list,
                        }, () => {
                            if (this.state.tabIndex !== index) {
                                this.setState({
                                    tabIndex: index,
                                })
                            }
                            this.props.setCurBasketballList(list,)
                        })
                    })

            }
        }


        // if (index === 4 && LocalStorageService.get('isLogin') === null) {
        //     statusList[4] = true
        //     this.setState({
        //         fetchStatus: [...statusList,],
        //     })
        // } else if (status === false) {
        //     ends[index] && ends[index](params)
        //         .then((resp) => {
        //             let list = resp.data.ok
        //             let lists = this.state.list
        //             lists[index] = list
        //             statusList[index] = true
        //             this.setState({
        //                 list: [
        //                     ...lists,
        //                 ],
        //                 fetchEnd: [
        //                     ...statusList,
        //                 ],
        //                 curList: list,
        //             }, () => {
        //                 if (this.state.tabIndex !== index) {
        //                     this.setState({
        //                         tabIndex: index,
        //                     })
        //                 }
        //                 this.props.setCurBasketballList(list,)
        //             })
        //         })
        // } else if (Array.isArray(status)) {
        //     const dateTabsActiveIndex = index === 2 ? this.state.scheduleTabsIndex : this.state.resultTabsIndex
        //     const dateTabsStatus = status[dateTabsActiveIndex]
        //     if (dateTabsStatus === false) {
        //         ends[index] && ends[index](params)
        //             .then((resp) => {
        //                 let list = resp.data.ok
        //                 let lists = this.state.list
        //                 let dateLists = lists[index]
        //                 dateLists[dateTabsActiveIndex] = list
        //                 lists[index] = dateLists
        //                 status[dateTabsActiveIndex] = true
        //                 statusList[index] = status
        //                 this.setState({
        //                     list: [
        //                         ...lists,
        //                     ],
        //                     fetchEnd: [
        //                         ...statusList,
        //                     ],
        //                     curList: list,
        //                 }, () => {
        //                     if (this.state.tabIndex !== index) {
        //                         this.setState({
        //                             tabIndex: index,
        //                         })
        //                     }
        //                     this.props.setCurBasketballList(list,)
        //                 })
        //             })
        //     } else {
        //         this.setState({
        //             tabIndex: index,
        //             curList: this.state.list[index][dateTabsActiveIndex],
        //         })
        //         this.props.setCurBasketballList(this.state.list[index][dateTabsActiveIndex],)
        //     }
        //
        // } else {
        //     this.setState({
        //         tabIndex: index,
        //         curList: this.state.list[index],
        //     })
        //     this.props.setCurBasketballList(this.state.list[index])
        // }

    }

    all = () => {
        return this.getList(0,)
    }

    fresh = () => {
        this.timerIdAll = setInterval(() => this.getList(0), 5000)
        this.timerIdLive = setInterval(() => this.getList(1), 5000)
    }

    onTabClick = (tab, index) => {
        const params = {}
        if (index === 2 || index === 3) {
            params.date = index === 2 ? this.state.scheduleTabs[this.state.scheduleTabsIndex].value : this.state.resultTabs[this.state.resultTabsIndex].value
            this.props.changeEventFilter({eventFilters: [],})
        }
        if (index === 4) {
            params.uid = this.uid
        }
        this.getList(index, params)
        const ps = this.state.positions
        ps[1] = index
        this.context.gamePagePosition.setPagePosition(ps)
        this.setState({
            ps: [...ps,]
        })
        if (index === 4) {
            this.props.setAtBasketballFollow(true)
        } else {
            this.props.setAtBasketballFollow(false)
        }
    }

    onDateTabSelected = (dateIndex, tabIndex) => {
        const key = tabIndex === 2 ? 'scheduleTabsIndex' : 'resultTabsIndex'
        this.setState({
            [key]: dateIndex,
        }, () => {
            const params = {}
            if (tabIndex === 2 || tabIndex === 3) {
                params.date = tabIndex === 2 ? this.state.scheduleTabs[this.state.scheduleTabsIndex].value : this.state.resultTabs[this.state.resultTabsIndex].value
            }
            const ps = this.state.positions
            const i = tabIndex === 2 ? 0 : 1
            ps[2][i] = dateIndex
            this.context.gamePagePosition.setPagePosition(ps)
            this.setState({
                ps: [...ps,]
            })
            this.getList(tabIndex, params)
        })
    }

    renderTabs = (tabIndex, lists, height,)  => {
        const tabs = tabIndex === 2 ? this.state.scheduleTabs : this.state.resultTabs
        const activeIndex = tabIndex === 2 ? this.state.scheduleTabsIndex : this.state.resultTabsIndex
        const datesLists = this.state.list[tabIndex]
        let listToRender = datesLists[activeIndex]
        const filters = this.props.eventFilters
        const hot = this.state.hot
        const hots = this.state.hots

        if (filters.length > 0) {
            listToRender = listToRender.filter(game => filters.findIndex(filter => filter.value.Name === game.Name) > -1)
        }
        if (hot) {
            listToRender = listToRender.filter(game => hots.includes(game.Name))
        }
        return <div
        >
            <DateTabs
                tabs={tabs}
                onTabSelected={(index) => this.onDateTabSelected(index, tabIndex)}
                today={this.today}
                activeIndex={activeIndex}
            />
            <div
                className='game-list-ctn'
                style={{height: height - 44,}}
            >
                {listToRender && listToRender.map((game, index) => <BasketballGameCard
                    key={index}
                    game={game}
                    markedList={this.state.markedList}
                />)}
            </div>
        </div>
    }

    render() {

        const downloadShow = this.props.downloadShow

        const mainTemplate = this.state.list.map((list, listIndex) => {
            const height = downloadShow
                ? document.documentElement.clientHeight - 50 - 60 - 43.5 - 43.5
                : document.documentElement.clientHeight - 50 - 43.5 - 43.5
            const style={
                height: height,
                background: '#F8F8F8',
            }
            const renderDataTabs = listIndex === 2 || listIndex === 3
            if (renderDataTabs) {
                return <div key={listIndex} style={style}>
                    {this.renderTabs(listIndex, list, height,)}
                </div>
            } else {
                const filters = this.props.eventFilters
                const hot = this.state.hot
                const hots = this.state.hots
                let listToRender = list

                if (filters.length > 0) {
                    listToRender = list.filter(game => filters.findIndex(filter => filter.value.Name === game.Name) > -1)
                }
                if (hot) {
                    listToRender = listToRender.filter(game => hots.includes(game.Name))
                }
                if (listIndex === 4 && listToRender.length > 0) {
                    listToRender = listToRender.filter(game => {
                        const today = moment()
                        const d = moment(game.Startt * 1000)
                        const diff = today.diff(d, 'days')
                        return diff >= 0
                    })
                }

                if (listIndex === 4 && listToRender.length === 0) {
                    const plsMark = <>
                        <NoDataPage text='没有任何数据呀'/>
                        <div style={{textAlign: 'center', marginTop: '8px'}}>
                            <span
                                style={{
                                    fontSize:12,
                                    fontWeight: '400',
                                    color: 'rgba(134,134,134,1)',
                                    lineHeight: '17px',
                                }}
                            >点击比赛详情页的‘</span>
                            <img alt='' src={EmptyStar} style={{width: 17, height: 16,}}/>
                            <span
                                style={{
                                    fontSize:12,
                                    fontWeight: '400',
                                    color: 'rgba(134,134,134,1)',
                                    lineHeight: '17px',}}
                            >’可关注比赛哟</span>
                        </div>
                    </>
                    return <div style={{background: '#F8F8F8', ...style}} key={listIndex}>
                        {plsMark}
                    </div>
                }

                return <div style={{background: '#F8F8F8', ...style}} key={listIndex}>
                    {listToRender.length === 0 ? <NoDataPage /> : listToRender.map((game, index) => <BasketballGameCard
                        key={index}
                        game={game}
                        markedList={this.state.markedList}
                    />)}
                </div>
            }
        })


        return <div
            style={{
                background: '#F8F8F8',
                position: 'relative',
                overflow: 'hidden',
            }}
        >
            <HotGameButton
                hot={this.state.hot}
                setHot={this.setHot}
            />
            <Tabs
                tabs={this.state.tabs}
                tabBarBackgroundColor='#183041'
                tabBarActiveTextColor='#FFFFFF'
                tabBarUnderlineStyle={{border: '2px #36C8B9 solid'}}
                tabBarInactiveTextColor='rgba(255, 255, 255, 0.4)'
                tabBarTextStyle={{fontSize: '14px',}}
                swipeable={false}
                onTabClick={(tab, index) => this.onTabClick(tab, index)}
                page={this.state.positions[1]}
                animated={false}
            >
                {mainTemplate}
            </Tabs>
        </div>
    }
}
Basketball.contextType = GlobalStore

const mapState = (state) => ({
    eventFilters: state.game.eventFilters,
})

const mapDispatch = dispatch => ({
    changeEventFilter: (payload) => dispatch.game.changeEventFilter(payload)
})

export default  connect(mapState, mapDispatch)(Basketball)
